const { myAssert, toTryCatch } = require("../../utils")
const { deleteFile, deleteDirectory } = require('../../utils/fileIO')
module.exports = {
    addDao: async (req, data) => {
        return toTryCatch(() => req.Model.create(data))
    },
    deleteDao: async (req, data) => {
        const res = await toTryCatch(() => req.Model.findOneAndDelete(data))
        if (res && res.type === 'error') return res
        if (req.Model.modelName === 'File') {
            const { path, type } = res
            if (type === 'file') {
                deleteFile(path)
            } else if (type === 'directory') {
                deleteDirectory(path)
            }
        }
        return res
    },
    updateDao: async (req, data) => {
        const queryOptions = {}
        if (req.Model.modelName === "User") {
            queryOptions.populate = 'camera'
        }
        if (req.Model.modelName === 'Website') {
            const url = data.url
            delete data.url
            return toTryCatch(() => req.Model.findOneAndUpdate({ url }, data, { new: true }))
        }
        const _id = data._id
        delete data._id
        return toTryCatch(() => req.Model.findOneAndUpdate({ _id }, data, { new: true }).setOptions(queryOptions))
    },
    getDao: async (req, data) => {
        return toTryCatch(() => req.Model.findOne(data))
    },
    getListDao: async (req, condition, start, pageSize) => {
        const queryOptions = {}
        if (req.Model.modelName === "User") {
            queryOptions.populate = 'camera'
        }
        if (req.Model.modelName === 'File') {
            queryOptions.populate = ['uploader', 'camera']
        }
        return toTryCatch(() => req.Model.find(condition).setOptions(queryOptions).skip(start).limit(pageSize))
    },
    getCountDao: async (req, data) => {
        return toTryCatch(() => req.Model.find().count())
    }
}
